package org.opu.doc2db.document.txtdoc.io;

import java.util.ArrayList;
import java.util.List;

public class CollumnWriter {

	private List<List<String>> collumn;
	private SettingsCalculator calculator;
	private int iter = 0;
	private boolean was = false;

	public CollumnWriter() {
		this(new SettingsCalculator());
	}

	public CollumnWriter(SettingsCalculator calculator) {
		this.calculator = calculator;
		collumn = new ArrayList<List<String>>();
	}

	public void add(List<String> data) {
		if (iter < collumn.size()){
			if (data == null){
				was = true;
			} else {
				List<String> list = collumn.get(iter);
				list.addAll(data);
			}
		} else {
			collumn.add(data);
		}
		iter ++;
	}

	public boolean addTo(int index, String data) {
		return collumn.get(index).add(data);
	}

	public List<String> get(int column) {
		return collumn.get(column);
	}

	public String get(int collumn, int row) {
		return this.collumn.get(collumn).get(row);
	}

	public int size() {
		return collumn.size();
	}

	public int size(int collumn) {
		return this.collumn.get(collumn).size();
	}
	
	public void flush(){
		iter = 0;
		
		if (!was){
			int maxCol = maxCol();
			int[] colSizes = colSizes();
			int i = 0;
			for (List<String> lst : collumn) {
				if (lst.size() < maxCol){
					lst.add(calculator.add(null, TextDocumentWriter.SPACE, colSizes[i]));
				}
				i++;
			}
		}
		
		was = false;
	}

	// //////////////////////////////////////////////////////////////
	// //////////////// For creating result string //////////////////
	// //////////////////////////////////////////////////////////////

	/**
	 * Return maximum amount of data in some column 
	 */
	int maxCol() {
		int max = 0;

		for (List<String> lst : collumn) {
			if (lst != null) {
				int size = lst.size();
				if (size > max) {
					max = size;
				}
			}
		}

		return max;
	}

	int[] colSizes() {
		int[] ret = new int[collumn.size()];

		int i = 0;
		for (List<String> lst : collumn) {
			String string = "";
			try {
				string = lst.get(0);
			} catch (Exception e) {
			}
			ret[i++] = string.length();
		}

		return ret;
	}

	@Override
	public String toString() {
		int maxCol = maxCol();
		int[] colSizes = colSizes();

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < maxCol; i++) {
			for (List<String> lst : collumn) {
				String string;
				
				try {
					string = lst.get(i);
				} catch (Exception e) {
					string = calculator.add(null, TextDocumentWriter.SPACE, colSizes[i]);
				}
				
				sb.append(string);
			}
			
			sb.append(calculator.getNewLine(null));
		}

		return sb.toString();
	}

}
